/*
** 鼠浩安,20181206
** 用户脚本初始化
** 提供工具方法，如自定义面板、动态加载js脚本等
** 对外开放对象有：
** 		pageTools:基础工具类
** 		shaToolPanel:面板工具类
*/

//协议
var HTTP_PROTOCOL = location.href.indexOf('https') > -1 ? 'https:' : 'http:';
//JQUERY地址
var JQUERY_URL = HTTP_PROTOCOL + '//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js';
//主机地址
var HOST =location.host;

//初始化
function PAGE_INIT(win) {

	//Tampermonkey-Window对象
	var TAMPERMONKEY_WINDOW = null;

	//防止多次加载
	if (window.____PAGE_INIT__) {
		return;
	}
	window.____PAGE_INIT__ = true;

	var jqeury_ajax = win.$ && $.ajax ? $.ajax : null;

	function silentDo(func){
		try{
			func();
		}catch(msg){}
	}
	function global(name,value){
		window[name]=value;
		silentDo(()=>unsafeWindow[name]=value);
	}

	if(window.jQuery){
		//global('jQuery',window.jQuery);
	}

	//pageTools
	(function () {

		var pageTools = {
			getWin: function () {
				return win;
			},
			setTAMPERMONKEY_WINDOW: function (win1) {
				TAMPERMONKEY_WINDOW = win1;
			},
			getTAMPERMONKEY_WINDOW: function(){
				return TAMPERMONKEY_WINDOW;
			},
			//输出调用追溯信息
			trace: function (args, count) {
				var caller = args.callee.caller;
				var i = 0;
				count = count || 10;
				console.log("***----------------------------------------  ** " + (i + 1));
				while (caller && i < count) {
					console.log(caller.toString());
					caller = caller.caller;
					i++;
					console.log("***---------------------------------------- ** " + (i + 1));
				}
			},
			//加载js
			loadScript: function (src, CB) {
				var script = document.createElement('script');
				script.onload = function () {
					if (CB) CB();
				};
				script.src = src;
				document.getElementsByTagName('head')[0].appendChild(script);
				return script;
			},
			//等待时机执行
			//conditionAction时机成熟的条件
			//执行的动作
			//检测轮训时间，默认100ms
			waitDo: function (conditionAction, doAction, time) {
				if (!conditionAction || !doAction) {
					return;
				}
				if (!time) {
					time = 100;
				}
				if (conditionAction()) {
					doAction();
				} else {
					var timer = setInterval(function () {
						if (conditionAction()) {
							clearInterval(timer);
							doAction();
						}
					}, time);
					setTimeout(() => clearInterval(timer), 5000);

				}

			},
			//延迟执行,用法:delay(1000).done(()=>console.log('1000ms had gone'));
			delay: function (ms) {
				var $=win.jQuery;
				var defer = $.Deferred();
				defer.delay = arguments.callee;
				if (this.done && $.isFunction(this.done)) {//等上个Deferred执行完后再执行延迟
					this.done(function () {
						setTimeout(function () {
							defer.resolve();
						}, ms);
					});
				} else {
					setTimeout(function () {
						defer.resolve();
					}, ms);
				}

				return defer;
			},
			//复制到剪切板,copy(123)
			copy: (function () {
				var fun = function (content) {
					var support = false;
					if (TAMPERMONKEY_WINDOW.GM_setClipboard) {
						support = true;
						var type = Object.prototype.toString.call(content);
						if (type == '[object Object]' || type == '[object Array]' || type == '[object Arguments]') {
							content = JSON.stringify(content);
						}
						TAMPERMONKEY_WINDOW.GM_setClipboard(content);
					}

					if (!support) {
						throw 'Not support';
					}
				};
				fun.toString = function () {
					return 'function copy() { [native code] }';
				};
				return fun;
			})(),
			//ajax请求
			ajax: function (opts) {
				var url=opts.url;
				if(jqeury_ajax && (url[0]==='/' || url.indexOf(HOST)>-1)){
					return jqeury_ajax(opts);
				}

				var config = win.jQuery.extend({
					method: 'GET',
					timeout: 10000,//超时10s
				}, opts);
				config.onload = function (data) {
					if (config.success) {
						var text = data.responseText;
						if (data.responseHeaders.indexOf('Content-Type: application/json') > -1) {
							text = JSON.parse(text);
						}
						config.success.call(this, text, data);
					}
				};
				(function(config){
					config.onerror= function (ins){
						console.error(config.method+' '+ins.finalUrl+' fail:'+ins.responseText);
					};
				})(config);
				return TAMPERMONKEY_WINDOW.GM_xmlhttpRequest(config);
			},
			//ajax-get请求
			ajax_get: function (url, data, onSuccess) {
				if(arguments.length==2 && typeof data =='function'){
					onSuccess=data;
					data=null;
				}
				return this.ajax({
					method: 'GET',
					url: url,
					data: data,
					success: onSuccess
				});
			},
			//ajax-post请求
			ajax_post: function (url, data, onSuccess) {
				if(arguments.length==2 && typeof data =='function'){
					onSuccess=data;
					data=null;
				}
				return this.ajax({
					method: 'POST',
					url: url,
					data: data,
					success: onSuccess
				});
			},


		};

		global('pageTools',pageTools);
		//引用JQUERY
		pageTools.delay(1000).done(() => {
			if (!win.jQuery) {
				pageTools.loadScript(JQUERY_URL);
			}

		});

	})();

	//shaToolPanel
	(function () {
		//初始化
		function init() {
			var jq = win.jQuery || {};
			var jqversion = jq.prototype.jquery;
			var $=win.jQuery;

			var div = document.createElement('div');
			document.body.appendChild(div);
			div.innerHTML = 'E';
			div.className = 'dxj_ext';
			var style = {
				position: 'fixed',
				right: 0,
				top: 0,
				opacity: 0.3,
				cursor: 'pointer',
				//zIndex:Number.MAX_SAFE_INTEGER,
				'z-index': Number.MAX_SAFE_INTEGER,
				fontSize: '20px',
				fontWeight: 'bold',
				backgroundColor: 'white',
				color: 'black'
			};

			for (var name in style) {
				div.style[name] = style[name];
			}

			div.addEventListener('click', function () {
				var panel = getPanel();
				panel.style.display = 'block';

			});

			function getPanel() {

				var thisFun = arguments.callee;
				if (thisFun._panel) {
					return thisFun._panel;
				}
				var panel = document.createElement('div');
				thisFun._panel = panel;
				panel.className = 'dxj_ext_panel';
				document.body.appendChild(panel);

				var style = {
					display: 'none',
					position: 'fixed',
					right: 0,
					top: 0,
					opacity: 1,
					cursor: 'pointer',
					paddingRight: '5px',
					color: '#1731776f',
					fontWeight: 'bold',
					zIndex: Math.pow(2, 64),
					//'z-index':'9999999992',
					backgroundColor: 'white',
				};
				for (var name in style) {
					panel.style[name] = style[name];
				}

				var html = `<div>jquery ${jqversion}</div>`;

				panel.innerHTML = html;
				panel.addEventListener('mouseleave', function () {
					getPanel().style.display = 'none';
				});
				return thisFun._panel;
			}

			//面板封装
			var panel = getPanel();
			var sha_tools_panel = {
				panel: $(panel),
				sid: 10000,
				zIndex: 999999999,
				//添加标签
				addLabel: function (labelHtml, clickFun) {
					var jq = $(labelHtml);
					if (jq.length == 0) {
						jq = $('<div></div>').html(labelHtml);
					}
					jq.appendTo(this.panel);
					jq.click(function () {
						clickFun.apply(this, arguments);
					});
				},
				//随机ID
				randomId: function (prefix) {
					if(typeof prefix =='undefined') prefix='';
					return prefix + (this.sid++);
				},
				//打开新页面
				addIframe: function (frameId1, iframeContent1, onBeforeLoad1) {
					var frameId = frameId1, iframeContent = iframeContent1, onBeforeLoad = onBeforeLoad1;
					if (arguments.length == 1) {
						frameId = null;
						iframeContent = arguments[0];
					} else if (arguments.length == 2 && typeof arguments[1] == 'function') {
						frameId = null;
						iframeContent = arguments[0];
						onBeforeLoad = arguments[1];
					}
					var txtId = this.randomId('_text_parent_var_');
					unsafeWindow.top[txtId] = iframeContent;
					var iframeId = frameId ? frameId : this.randomId('iframe_id_');
					if ($('#webkit-xml-viewer-source-xml').length > 0) {
						var xmlEle = $('#webkit-xml-viewer-source-xml');
						xmlEle.hide().next().hide().next().hide();
						$('body').append('<iframe src="" id="' + iframeId + '" class="sha_iframe"></iframe>');
					} else {
						$('body').append('<iframe src="" id="' + iframeId + '" class="sha_iframe"></iframe>');
					}

					var iframe = $('#' + iframeId);
					iframe.on('close', function () {
						$(this).next().trigger('click');
					});
					if (onBeforeLoad) {
						onBeforeLoad.call(iframe);
					}

					iframe.css({
						width: 'calc(100% - 30px)', height: 'calc(100% - 30px)', 'border': '5px solid green', 'background-color': 'white', position: 'fixed',
						'z-index': this.zIndex++, 'border-radius': '30px', left: '10px', top: '15px'
					});

					iframe.on('load', function () {
						var iframe = $(this);

						var styles = `
<style>

</style>
`;
						var zIndex = iframe.css('z-index') - 0 + 1;
						var subHtml = `
<div class="btn_close" title="点击关闭"
	style="position:fixed;right: 8px;top: 13px;text-align: center;width: 18px;height: 18px;color:green;vertical-align: middle;cursor:pointer;z-index:${zIndex};background-color:white;border:3px solid green;border-radius: 20px;font-size:16px;"
	onclick="$(this).prev().trigger('unload').remove().end().remove()" onmouseenter="$(this).css('color','red')" onmouseleave="$(this).css('color','green')">
	<span style="position:relative;top:-2px;">X</span>
</div>
`;

						//iframe[0].contentWindow.$('body').append(subHtml);
						iframe.after(subHtml);
						//处理内部iframe调用关闭
						var closeBtn = iframe.next();
						this.contentWindow.$(this.contentWindow.document).on('close', function () {
							closeBtn.trigger('click');
						});
					});

					iframe[0].src = "javascript:top." + txtId;

				},
				//ajax请求
				ajax: function (opts) {
					return pageTools.ajax.apply(this,arguments);
					/*var config = $.extend({
						method: 'GET',
					}, opts);
					config.onload = function (data) {
						if (config.success) {
							var text = data.responseText;
							if (data.responseHeaders.indexOf('Content-Type: application/json') > -1) {
								text = JSON.parse(text);
							}
							config.success.call(this, text, data);
						}
					};
					debugger;
					config.onerror= function (){
						console.log("ajax onerror",arguments);

					};
					return TAMPERMONKEY_WINDOW.GM_xmlhttpRequest(config);*/
				},
				//ajax-get请求
				ajax_get: function (url, data, onSuccess) {
					return this.ajax({
						method: 'GET',
						url: url,
						data: data,
						success: onSuccess
					});
				},
				//ajax-post请求
				ajax_post: function (url, data, onSuccess) {
					return this.ajax({
						method: 'POST',
						url: url,
						data: data,
						success: onSuccess
					});
				},

			};

			//初始化默认工具
			(function (tool) {

				tool.addLabel('API调试', function () {
					var url = HTTP_PROTOCOL + '//haoan.gitee.local.io/static_tools/pages/api_test.html?_t=' + new Date().getTime();
					console.log('API调试 url: '+url);
					tool.ajax_get(url, null, function (d) {
						tool.addIframe(d);
					});
				});

			})(sha_tools_panel);

			//win.sha_tools_panel = shaToolPanel = sha_tools_panel;
			global('sha_tools_panel',sha_tools_panel);
			global('shaToolPanel',sha_tools_panel);
		}

		console.time('sha_tools_panel ready');
		pageTools.waitDo(() => document.body && pageTools.getWin().jQuery, () => {
			init();
			console.timeEnd('sha_tools_panel ready');
		});

	})();


	(function(){
		Object.funs=function(obj){
			if(obj==null || typeof obj=='undefined'){
				return {};
			}
			var funNames = Object.keys(obj).filter(key=>typeof obj[key] =='function');
			var ret={};
			funNames.forEach(key=>{
				ret[key]=obj[key];
			});
			return ret;
		};

	})();

}

try{
	if(!unsafeWindow){
		window.unsafeWindow=window;
	}
}catch(msg){}

(function(){
	//执行初始化
	try{
		PAGE_INIT(unsafeWindow);
	}catch(msg){
		window.____PAGE_INIT__=false;
		PAGE_INIT(window);
	}

})();



